import 'package:get/get.dart';
import 'package:raze/lore/glyph/answer_essence.dart';
import 'package:raze/lore/glyph/like_record_essence.dart';
import 'package:raze/lore/glyph/question_essence.dart';

/// 问答状态管理
/// 全局问答状态，提供问题发布、回答、点赞等功能
class QnAChronicle extends GetxController {
  // 所有问题列表
  final _questionList = <QuestionEssence>[].obs;

  // 所有回答列表
  final _answerList = <AnswerEssence>[].obs;

  // 所有点赞记录列表
  final _likeRecordList = <LikeRecordEssence>[].obs;

  /// 获取所有问题列表
  List<QuestionEssence> get questionList => _questionList;

  /// 获取所有回答列表
  List<AnswerEssence> get answerList => _answerList;

  @override
  void onInit() {
    super.onInit();
    _initializeDefaultQnA();
  }

  /// 初始化默认问答数据
  void _initializeDefaultQnA() {
    final now = DateTime.now();

    // 初始化问题
    _questionList.value = [
      QuestionEssence(
        id: '1',
        userId: '2',
        content: 'Why do leaves look greener after rain?',
        likeCount: 8,
        createTime: now.subtract(const Duration(days: 3)),
      ),
      QuestionEssence(
        id: '2',
        userId: '3',
        content: 'Why do some leaves hold water droplets better?',
        likeCount: 10,
        createTime: now.subtract(const Duration(days: 5)),
      ),
      QuestionEssence(
        id: '3',
        userId: '1',
        content: 'Do plants really grow faster after rain?',
        likeCount: 9,
        createTime: now.subtract(const Duration(days: 2)),
      ),
    ];

    // 初始化回答
    _answerList.value = [
      // 问题1的回答
      AnswerEssence(
        id: '1',
        questionId: '1',
        userId: '4',
        content:
            'This is because rainwater washes away dust and pollutants from the leaf surface, allowing more light to reach the chloroplasts. Plus, the moisture helps the stomata open wider, making photosynthesis more efficient!',
        likeCount: 0,
        createTime: now.subtract(const Duration(days: 3, hours: 2)),
      ),
      AnswerEssence(
        id: '2',
        questionId: '1',
        userId: '5',
        content:
            'The rainwater also contains nitrogen compounds that act as natural fertilizer. Your plants are literally "breathing" better after the rain!',
        likeCount: 0,
        createTime: now.subtract(const Duration(days: 2, hours: 18)),
      ),
      // 问题2的回答
      AnswerEssence(
        id: '3',
        questionId: '2',
        userId: '1',
        content:
            'This depends on the leaf\'s surface structure! Waxy leaves (like those of water lilies) have hydrophobic surfaces that repel water, causing droplets to bead up. Hairy leaves can trap water in tiny spaces between the hairs.',
        likeCount: 0,
        createTime: now.subtract(const Duration(days: 5, hours: 4)),
      ),
      AnswerEssence(
        id: '4',
        questionId: '2',
        userId: '6',
        content:
            'The shape and angle of leaves also matter. Some leaves are designed to channel water toward the roots, while others let it roll off to prevent fungal growth.',
        likeCount: 0,
        createTime: now.subtract(const Duration(days: 4, hours: 12)),
      ),
      // 问题3的回答
      AnswerEssence(
        id: '5',
        questionId: '3',
        userId: '7',
        content:
            'It\'s not your imagination! Rainwater provides moisture that allows roots to absorb nutrients more efficiently. The soil also becomes softer, making it easier for roots to expand and grow.',
        likeCount: 0,
        createTime: now.subtract(const Duration(days: 2, hours: 5)),
      ),
      AnswerEssence(
        id: '6',
        questionId: '3',
        userId: '2',
        content:
            'Additionally, the increased humidity after rain helps reduce water loss through transpiration, allowing plants to allocate more energy toward growth rather than water conservation.',
        likeCount: 0,
        createTime: now.subtract(const Duration(days: 1, hours: 15)),
      ),
    ];

    // 初始化点赞记录
    // 问题1的点赞（8个赞）- 用户1,3,4,5,6,7,8,10点赞，用户2,9未点赞
    _likeRecordList.value = [
      LikeRecordEssence(userId: '1', targetId: '1'),
      LikeRecordEssence(userId: '3', targetId: '1'),
      LikeRecordEssence(userId: '4', targetId: '1'),
      LikeRecordEssence(userId: '5', targetId: '1'),
      LikeRecordEssence(userId: '6', targetId: '1'),
      LikeRecordEssence(userId: '7', targetId: '1'),
      LikeRecordEssence(userId: '8', targetId: '1'),
      LikeRecordEssence(userId: '10', targetId: '1'),
      // 问题2的点赞（10个赞）- 所有用户都点赞
      LikeRecordEssence(userId: '1', targetId: '2'),
      LikeRecordEssence(userId: '2', targetId: '2'),
      LikeRecordEssence(userId: '3', targetId: '2'),
      LikeRecordEssence(userId: '4', targetId: '2'),
      LikeRecordEssence(userId: '5', targetId: '2'),
      LikeRecordEssence(userId: '6', targetId: '2'),
      LikeRecordEssence(userId: '7', targetId: '2'),
      LikeRecordEssence(userId: '8', targetId: '2'),
      LikeRecordEssence(userId: '9', targetId: '2'),
      LikeRecordEssence(userId: '10', targetId: '2'),
      // 问题3的点赞（9个赞）- 用户1-9点赞，用户10未点赞
      LikeRecordEssence(userId: '1', targetId: '3'),
      LikeRecordEssence(userId: '2', targetId: '3'),
      LikeRecordEssence(userId: '3', targetId: '3'),
      LikeRecordEssence(userId: '4', targetId: '3'),
      LikeRecordEssence(userId: '5', targetId: '3'),
      LikeRecordEssence(userId: '6', targetId: '3'),
      LikeRecordEssence(userId: '7', targetId: '3'),
      LikeRecordEssence(userId: '8', targetId: '3'),
      LikeRecordEssence(userId: '9', targetId: '3'),
    ];
  }

  /// 发布问题
  /// [userId] 发布者用户ID
  /// [content] 问题内容
  /// 返回创建的问题ID
  String publishQuestion(String userId, String content) {
    final newId = (_questionList.length + 1).toString();
    final newQuestion = QuestionEssence(
      id: newId,
      userId: userId,
      content: content,
      likeCount: 0,
      createTime: DateTime.now(),
    );
    _questionList.add(newQuestion);
    return newId;
  }

  /// 回答问题
  /// [questionId] 问题ID
  /// [userId] 回答者用户ID
  /// [content] 回答内容
  /// 返回创建的回答ID
  String submitAnswer(String questionId, String userId, String content) {
    final newId = (_answerList.length + 1).toString();
    final newAnswer = AnswerEssence(
      id: newId,
      questionId: questionId,
      userId: userId,
      content: content,
      likeCount: 0,
      createTime: DateTime.now(),
    );
    _answerList.add(newAnswer);
    return newId;
  }

  /// 对问题点赞
  /// [userId] 点赞用户ID
  /// [questionId] 问题ID
  /// 返回操作结果，成功返回true，失败返回false（已点赞或问题不存在）
  bool likeQuestion(String userId, String questionId) {
    // 检查是否已点赞
    final hasLiked = _likeRecordList.any(
      (record) => record.userId == userId && record.targetId == questionId,
    );

    if (hasLiked) {
      return false; // 已点赞
    }

    final index = _questionList.indexWhere((q) => q.id == questionId);
    if (index == -1) {
      return false; // 问题不存在
    }

    // 添加点赞记录
    _likeRecordList.add(
      LikeRecordEssence(userId: userId, targetId: questionId),
    );

    // 更新点赞数
    final question = _questionList[index];
    _questionList[index] = question.copyWith(likeCount: question.likeCount + 1);

    // 触发响应式更新
    _questionList.refresh();

    return true;
  }

  /// 取消对问题的点赞
  /// [userId] 取消点赞的用户ID
  /// [questionId] 问题ID
  /// 返回操作结果，成功返回true，失败返回false（未点赞或问题不存在）
  bool unlikeQuestion(String userId, String questionId) {
    // 检查是否已点赞
    final hasLiked = _likeRecordList.any(
      (record) => record.userId == userId && record.targetId == questionId,
    );

    if (!hasLiked) {
      return false; // 未点赞
    }

    final index = _questionList.indexWhere((q) => q.id == questionId);
    if (index == -1) {
      return false; // 问题不存在
    }

    // 移除点赞记录
    _likeRecordList.removeWhere(
      (record) => record.userId == userId && record.targetId == questionId,
    );

    // 更新点赞数
    final question = _questionList[index];
    final newLikeCount = question.likeCount > 0 ? question.likeCount - 1 : 0;
    _questionList[index] = question.copyWith(likeCount: newLikeCount);

    // 触发响应式更新
    _questionList.refresh();

    return true;
  }

  /// 检查用户是否已对问题点赞
  /// [userId] 用户ID
  /// [questionId] 问题ID
  /// 返回是否已点赞
  bool checkQuestionLiked(String userId, String questionId) {
    return _likeRecordList.any(
      (record) => record.userId == userId && record.targetId == questionId,
    );
  }

  /// 根据ID查询问题
  /// [questionId] 问题ID
  /// 返回问题，不存在返回null
  QuestionEssence? queryQuestionById(String questionId) {
    return _questionList.firstWhereOrNull((q) => q.id == questionId);
  }

  /// 获取问题的所有回答
  /// [questionId] 问题ID
  /// 返回该问题的所有回答列表
  List<AnswerEssence> fetchAnswersByQuestionId(String questionId) {
    return _answerList
        .where((answer) => answer.questionId == questionId)
        .toList()
      ..sort((a, b) => b.createTime.compareTo(a.createTime));
  }

  /// 删除问题
  /// [questionId] 问题ID
  /// 返回操作结果，成功返回true，失败返回false（问题不存在）
  bool deleteQuestionById(String questionId) {
    final index = _questionList.indexWhere((q) => q.id == questionId);
    if (index == -1) {
      return false; // 问题不存在
    }

    // 删除问题
    _questionList.removeAt(index);

    // 删除该问题的所有回答
    _answerList.removeWhere((answer) => answer.questionId == questionId);

    // 删除该问题的所有点赞记录
    _likeRecordList.removeWhere((record) => record.targetId == questionId);

    return true;
  }

  /// 删除回答
  /// [answerId] 回答ID
  /// 返回操作结果，成功返回true，失败返回false（回答不存在）
  bool eraseAnswerById(String answerId) {
    final index = _answerList.indexWhere((a) => a.id == answerId);
    if (index == -1) {
      return false; // 回答不存在
    }

    // 删除回答
    _answerList.removeAt(index);

    return true;
  }
}
